Imagine navigating a vast landscape. Whether you are driving on a straight highway (a vector) or hiking a winding forest trail (a list), you need a universal GPS. In C++, that GPS is the Iterator.
The Bridge of Generic Programming
Iterators act as a generalized mechanism for navigating container elements, serving as a bridge between algorithms and data structures. By utilizing a uniform interface (begin/end), C++ achieves Generic Programming. This allows the same logic to process diverse collections without the programmer needing to know the underlying memory layout.
⚠️ Iterator Invalidation: CRITICAL: Any loop that uses an iterator to traverse a container must NOT add elements to that container. Doing so may render existing iterators "stale" (invalidated), leading to undefined behavior or program crashes.
Standard Operations
The begin returns an iterator to the first element, while end returns a sentinel representing one past the last element.
*iter: Dereference to access the element.++iter/--iter: Movement.==/!=: Equality operators to check position.
TERMINAL
bash — 80x24
> Ready. Click "Run" to execute.
>